package com.xiaozhengkeji.starbootserver.listener;

import cn.hutool.core.util.RandomUtil;
import com.xiaozhengkeji.starbootserver.base.redis.VerifyBaseRedis;
import com.xiaozhengkeji.starbootserver.bus.services.MailBoxService;
import com.xiaozhengkeji.starbootserver.config.RedisIndexConfig;
import com.xiaozhengkeji.starbootserver.events.SystemUserRegisterEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import wiki.xsx.core.util.RedisUtil;

import java.util.concurrent.TimeUnit;

/**
 * 邮件相关监听并且实现
 */
@Slf4j
@Component
public class MailBoxListener {

    MailBoxService mailBoxService;
    VerifyBaseRedis verifyBaseRedis;

    @Autowired
    public MailBoxListener(MailBoxService mailBoxService, VerifyBaseRedis verifyBaseRedis) {
        this.mailBoxService = mailBoxService;
        this.verifyBaseRedis = verifyBaseRedis;
    }


    @Async("PublicTaskExecutor")
    @EventListener
    @Order(1)
    public void systemUserLoginListener(SystemUserRegisterEvent systemUserRegisterEvent) {
        if (systemUserRegisterEvent.getHasToSendMail()) {
            // 发送邮件
            String vc = RandomUtil.randomString(6);
            verifyBaseRedis.setEmailVerificationCode(systemUserRegisterEvent.getMailbox(), vc);
            log.info("发送注册邮件Addr{},验证码{}", systemUserRegisterEvent.getMailbox(), vc);
            mailBoxService.sendRegisterUserEmail(systemUserRegisterEvent.getMailbox(), vc, systemUserRegisterEvent.getUsername());
        }

        log.info("用户请求发送邮件：" + systemUserRegisterEvent.getUsername());
    }
}
